<template>
  <div>
    <!-- 排行榜
        http://127.0.0.1:3000/toplist
        http://127.0.0.1:3000/playlist/detail?id=19723756 -->
    <div class="toplist">
      <div class="item" v-for="(item, index) in toplists" :key="index" >
        <a href="javascript:(0)" @click="getId(item.id)">
          <div class="img">
              <img :src="item.coverImgUrl+'?param=50y50'" alt="">
          </div>
          <ul>
            <li v-for="(key, i) in item.getTopListsDetail" :key="i">
              {{ i + 1 }}. {{ key.name }} -- {{ key.ar[0].name }}
            </li>
          </ul>
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import { getTopLists, getTopListsDetail } from "../api/rank";

export default {
  data() {
    return {
      toplists: "",
    };
  },
  // 组件路由最早钩子  守卫在导航前被调用
  beforeRouteEnter(to, from, next) {
    // 获取分类数据图片
    getTopLists({ limit: 10 }).then((data) => {
      // next(to) 是一个函数，next函数决定路由是否跳转
      next((vm) => vm.getTopListsDetailFun(data.list));
    });
  },
  methods: {
    getId(id){
      this.$router.push({
        path:'/recommend/ranklist',
        query:{id}
      })
    },
    getTopListsDetailFun(toplistsData) {
      this.toplists = toplistsData;
      // 遍历图片数据的id，再请求列表数据
      for (let item in toplistsData) {
        getTopListsDetail({ id: toplistsData[item].id }).then((data) => {
          if (data.playlist.tracks.length) {
            // $set是为了解决双向数据绑定失效的问题   但数据没有被双向绑定的时候，我们就需要使用set了    
            this.$set(
              this.toplists[item],
              "getTopListsDetail",
              data.playlist.tracks.slice(0, 3)
            );
          }
        });
      }
    },
  },
};
</script>

<style lang="less">
.toplist {
  padding: 15px;
  .item {
    padding: 4px 0px;
    border-bottom: 2px solid #e3e4e4;
    a {
      display: flex;
      .img {
        flex: 0 0 154px;
        height: 154px;
        background-color: #F2F3F4;
        img {
          width: 100%;
        }
      }
      ul {
        padding-top: 10px;
        flex: 1;
        li {
          width: 190px;
          font-size: 14px;
          color: #030006;
          line-height: 46px;
          text-indent: 30px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
